<template>
  <!-- 动态渲染tabs历史菜单 -->
  <el-tabs
    v-model="store.activeIndexTab"
    type="card"
    :closable="true"
    @tab-click="handleTabsclick"
    @tab-remove="handleTabRemove"
    class="demo-tabs tabs"
  >
    <el-tab-pane
      class="tabs"
      v-for="item in store.menuTabs"
      :label="item"
      :name="item"
    >
    </el-tab-pane>
  </el-tabs>
</template>
<script setup>
import { ElMessage } from 'element-plus'
import { useStore } from '@/store/user'
import { useRouter } from 'vue-router'
import ComonUtils from '@/utils/ComonUtils'

const store = useStore()
const router = useRouter()
//点击tabs路由跳转
const handleTabsclick = (tab) => {
  router.push({
    name: tab.props.name,
  })
}
//关闭
const handleTabRemove = (tab) => {
  console.log(tab)
  if (tab == '首页') {
    ElMessage('首页不可关闭')
  } else {
    //删除数组中最后一个
    ComonUtils.removeArray(store.menuTabs, tab)
    //选中数组中的最后一个值
    store.activeIndexTab = store.menuTabs[store.menuTabs.length - 1]
    //跳转路由
    router.push({
      name: store.activeIndexTab,
    })
  }
}

//监听路由状态，添加或选中menuTabs
onBeforeRouteUpdate((to) => {
  //设置一个状态，判断是否本地存储是否存在tabs名称
  let flag = false
  //循环存储在本地已打开的菜单
  for (let tab of store.menuTabs) {
    //判断是否本地存储和当前点击是否相同，相同则跳转路由，不添加本地存储
    if (to.name == tab) {
      store.activeIndexTab = tab
      // 将状态打开，并跳出循环
      flag = true
      break
    }
  }
  //本地不存在tabs名称，则将点击的tabs名称存储到本地
  if (!flag) {
    store.menuTabs.push(to.name)
    store.activeIndexTab = to.name
  }
})
</script>
<style>
.demo-tabs > .el-tabs__header {
  background-color: #fff;
}
</style>
